package com.cheche.dn.infrastructure.security;

import com.cheche.dn.Result;
import com.cheche.dn.domain.Apis;
import com.cheche.dn.domain.user.User;
import com.cheche.dn.error.ErrorCode;
import com.cheche.dn.utils.JsonUtil;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.*;
import org.springframework.security.authentication.encoding.MessageDigestPasswordEncoder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.web.filter.GenericFilterBean;
import org.springframework.web.util.UrlPathHelper;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AuthenticationFilter extends GenericFilterBean {

    private final static Logger logger = LoggerFactory.getLogger(AuthenticationFilter.class);
    public static final String TOKEN_SESSION_KEY = "token";
    public static final String USER_SESSION_KEY = "user";
    private AuthenticationManager authenticationManager;
    
    public AuthenticationFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = asHttp(request);
        HttpServletResponse httpResponse = asHttp(response);

        Optional<String> username = Optional.fromNullable(httpRequest.getParameter("X-Auth-Username"));
        Optional<String> password = Optional.fromNullable(httpRequest.getParameter("X-Auth-Password"));
        Optional<String> token = Optional.fromNullable(httpRequest.getHeader("X-Auth-Token"));
//        Optional<String> third = Optional.fromNullable(httpRequest.getHeader("X-Auth-Third"));
//        Optional<String> type = Optional.fromNullable(httpRequest.getHeader("X-Auth-Type"));

        if (credentialsMissing(username, password)) {
            User user = (User) httpRequest.getAttribute("X-Auth-User");
            if (user != null) {
                username = Optional.fromNullable(user.getUsername());
                password = Optional.fromNullable(user.getPassword());
            }
        }

        boolean isAdmin = adminToAuthenticate(httpRequest);

        String resourceURL = new UrlPathHelper().getPathWithinApplication(httpRequest);

        try {
            if (postToAuthenticate(httpRequest, resourceURL) && !isAdmin) {
                logger.debug("Trying to authenticate user {} by X-Auth-Username method", username.toString());
                processUsernamePasswordAuthentication(httpResponse, username, password);
                return;
            }

            if (token.isPresent() && mappingToAuthenticate(httpRequest, resourceURL)) {
                logger.debug("Trying to authenticate user by X-Auth-Token method. Token: {}", token);
                processTokenAuthentication(httpRequest, token);
            }

            logger.debug("AuthenticationFilter is passing request down the filter chain");
            addSessionContextToLogging();
            chain.doFilter(request, response);
        } catch (InternalAuthenticationServiceException internalAuthenticationServiceException) {
            SecurityContextHolder.clearContext();
            logger.error("Internal authentication service exception", internalAuthenticationServiceException);
            httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, internalAuthenticationServiceException.getMessage());
        } catch (CredentialsExpiredException credentialsExpiredException) {
            SecurityContextHolder.clearContext();
            returnError(httpResponse, ErrorCode.TOKEN_EXPIRED);
        } catch (UsernameNotFoundException usernameNotFoundException) {
            SecurityContextHolder.clearContext();
            returnError(httpResponse, ErrorCode.USER_NOT_EXIST);
        } catch (BadCredentialsException badCredentialsException) {
            SecurityContextHolder.clearContext();
            returnError(httpResponse, ErrorCode.PASSWORD_ERROR);
        } catch (AuthenticationCredentialsNotFoundException authenticationCredentialsNotFoundException) {
            SecurityContextHolder.clearContext();
            returnError(httpResponse, ErrorCode.ERROR);
        } catch (AuthenticationException authenticationException) {
            SecurityContextHolder.clearContext();
            httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, authenticationException.getMessage());
        } finally {
            MDC.remove(TOKEN_SESSION_KEY);
            MDC.remove(USER_SESSION_KEY);
        }
    }

    private void addSessionContextToLogging() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String tokenValue = "EMPTY";
        if (authentication != null && !Strings.isNullOrEmpty(authentication.getDetails().toString())) {
            MessageDigestPasswordEncoder encoder = new MessageDigestPasswordEncoder("SHA-1");
            tokenValue = encoder.encodePassword(authentication.getDetails().toString(), "not_so_random_salt");
        }
        MDC.put(TOKEN_SESSION_KEY, tokenValue);

        String userValue = "EMPTY";
        if (authentication != null && !Strings.isNullOrEmpty(authentication.getPrincipal().toString())) {
            userValue = authentication.getPrincipal().toString();
        }
        MDC.put(USER_SESSION_KEY, userValue);
    }

    private HttpServletRequest asHttp(ServletRequest request) {
        return (HttpServletRequest) request;
    }

    private HttpServletResponse asHttp(ServletResponse response) {
        return (HttpServletResponse) response;
    }

    private boolean postToAuthenticate(HttpServletRequest httpRequest, String resourcePath) {
        return Apis.AUTHENTICATE_URL.equalsIgnoreCase(resourcePath) && httpRequest.getMethod().toUpperCase().equals(HttpMethod.POST.name());
    }

    private boolean credentialsMissing(Optional<String> username, Optional<String> password) {
        return !username.isPresent() || !password.isPresent();
    }

    private boolean adminToAuthenticate(HttpServletRequest httpRequest) {
        String isAdminHeader = httpRequest.getHeader("Is-Admin");
        return isAdminHeader != null && isAdminHeader.equalsIgnoreCase("true");
    }

    private boolean mappingToAuthenticate(HttpServletRequest httpRequest, String resourceURL) {
        for (Apis.Mapping mapping : Apis.OPEN_MAPPINGS) {
            if (mapping.getUrl().equals(resourceURL)) {
                if (mapping.getMethod() == null || httpRequest.getMethod().toUpperCase().equals(mapping.getMethod().name())) {
                    return false;
                }
            }
        }
        return true;
    }

    private void processUsernamePasswordAuthentication(HttpServletResponse httpResponse, Optional<String> username, Optional<String> password) throws IOException {
        Authentication resultOfAuthentication = tryToAuthenticateWithUsernameAndPassword(username, password);
        SecurityContextHolder.getContext().setAuthentication(resultOfAuthentication);
        returnSuccess(httpResponse, resultOfAuthentication);
    }

    private Authentication tryToAuthenticateWithUsernameAndPassword(Optional<String> username, Optional<String> password) {
        Authentication requestAuthentication = new UsernamePasswordAuthenticationToken(username, password);
        return tryToAuthenticate(requestAuthentication);
    }

    private void processTokenAuthentication(HttpServletRequest httpRequest, Optional<String> token) {
        Authentication resultOfAuthentication = tryToAuthenticateWithToken(token);
        SecurityContextHolder.getContext().setAuthentication(resultOfAuthentication);
        Object principal = resultOfAuthentication.getPrincipal();
        httpRequest.setAttribute(principal.getClass().getName(), principal);
    }

    private Authentication tryToAuthenticateWithToken(Optional<String> token) {
        PreAuthenticatedAuthenticationToken requestAuthentication = new PreAuthenticatedAuthenticationToken(null, token);
        return tryToAuthenticate(requestAuthentication);
    }

    private Authentication tryToAuthenticate(Authentication requestAuthentication) {
        Authentication responseAuthentication = authenticationManager.authenticate(requestAuthentication);
        if (responseAuthentication == null || !responseAuthentication.isAuthenticated()) {
            throw new InternalAuthenticationServiceException("Unable to authenticate Domain User for provided credentials");
        }
        logger.debug("User successfully authenticated");
        return responseAuthentication;
    }

    private void returnSuccess(HttpServletResponse httpResponse,
                               Authentication resultOfAuthentication) throws IOException {
        httpResponse.setStatus(HttpServletResponse.SC_OK);
        Object entity = resultOfAuthentication.getPrincipal();
        Result result = Result.success("token", resultOfAuthentication.getDetails().toString()).
                append(entity.getClass().getSimpleName().toLowerCase(), entity);
        returnResult(httpResponse, result);
    }

    private void returnError(HttpServletResponse httpResponse, ErrorCode errorCode) {
        httpResponse.setStatus(HttpServletResponse.SC_OK);
        Result result = Result.error(errorCode);
        if (errorCode.equals(ErrorCode.ERROR)) {
            result = Result.error(errorCode, "Parameter error");
        }
        try {
            returnResult(httpResponse, result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void returnResult(HttpServletResponse httpResponse, Object result) throws IOException {
        String jsonResponse = JsonUtil.toJson(result);
        httpResponse.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        httpResponse.getWriter().print(jsonResponse);
    }
}
